using System.Collections;
using System.Collections.Generic;
using System.Xml;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    private Transform frontCheck;
    private Rigidbody2D enemyBody;
    public float enemySpeed = 2f;

    public float HP = 2f;
    public Sprite deadEnemy;
    public Sprite damageEnemy;
    public float spinMax = 100;
    public float spinMin = -100;

    private SpriteRenderer ren;
    private bool dead = false;
    // Start is called before the first frame update
    void Start()
    {
        frontCheck = transform.Find("FrontCheck").transform;
        enemyBody = GetComponent<Rigidbody2D>();
        ren = transform.Find("body").GetComponent<SpriteRenderer>();
    }

    public void Hurt()
    {
        HP--;
    }

    void Death()
    {
        SpriteRenderer[] otherSprites = GetComponentsInChildren<SpriteRenderer>();
        foreach (SpriteRenderer sp in otherSprites)
            sp.enabled = false;

        ren.enabled = true;
        ren.sprite = deadEnemy;

        dead = true;
        enemyBody.freezeRotation = false;

        enemyBody.AddTorque(Random.Range(spinMin, spinMax));

        Collider2D[] collider2s = GetComponents<Collider2D>();
        foreach (Collider2D collider in collider2s)
            collider.isTrigger = true;

    }

    void Flip()
    {
        Vector3 localScale = transform.localScale;
        localScale.x *= -1;
        transform.localScale = localScale;
    }

    private void FixedUpdate()
    {
        if (HP == 1 && damageEnemy != null)
        {
            ren.sprite = damageEnemy;
        }
        if ((HP <= 0 && !dead))
            Death();
    }

    // Update is called once per frame
    void Update()
    {
        Collider2D[] cols = Physics2D.OverlapPointAll(frontCheck.position, 1 << LayerMask.NameToLayer("Ground"));
        foreach (Collider2D col in cols)
        {
            if (col.tag == "UFO")
            {
                Flip();
                break;
            }
        }

        enemyBody.velocity = new Vector2(enemySpeed * transform.localScale.x, enemyBody.velocity.y);
    }
}
